const state = {
    data: {
        nodes: [], // 节点信息
        lines: [], // 连线信息
    },
    curNode: {}, // 当前节点
    curLine: {}, // 当前连线
};

const mutations = {
    // 节点数组
    SET_NODES: (state, data) => {
        state.data.nodes = data;
    },
    // 连线数组
    SET_LINES: (state, data) => {
        state.data.lines = data;
    },
    // 当前节点
    SET_CUR_NODE: (state, data) => {
        state.curNode = null;
        state.curNode = data;
    },
    // 当前线
    SET_CUR_LINE: (state, data) => {
        state.curLine = null;
        state.curLine = data;
    },
    SET_DATA: (state, data) => {
        state.data = null;
        state.data = data;
    },
    EXECUTE_NODE: (state, data) => {
        switch (data.op) {
            case 'add':
                state.data.nodes.push(data.com);
                break;
            case 'delete':
                state.data.nodes = state.data.nodes.filter((node) => {
                    if (node.id === data.com.nodeId) {
                        return false;
                    }
                    return true;
                });
                break;
            default:
                console.log('不执行此命令');
                break;
        }
    },
    EXECUTE_LINE: (state, data) => {
        switch (data.op) {
            case 'add':
                state.data.lines.push(data.com);
                break;
            case 'update':
                state.data.lines = state.data.lines.map((line) => {
                    if (line.from === data.com.from && line.to === data.com.to) {
                        return { ...line, ...data.com };
                    }
                    return line;
                });
                break;
            default:
                console.log('不执行此命令');
                break;
        }
    },
};

const actions = {
    // 节点数组
    setNodes: ({ commit }, data) => {
        commit('SET_NODES', data);
    },
    setLines: ({ commit }, data) => {
        commit('SET_LINES', data);
    },
    setCurNode: ({ commit }, data) => {
        commit('SET_CUR_NODE', data);
    },
    setCurLine: ({ commit }, data) => {
        commit('SET_CUR_LINE', data);
    },
    setData: ({ commit }, data) => {
        commit('SET_DATA', data);
    },
    executeNode: ({ commit }, data) => {
        commit('EXECUTE_NODE', data);
    },
    executeLine: ({ commit }, data) => {
        commit('EXECUTE_LINE', data);
    },
};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
};
